#include "Rpc.h"
#include "ServerSyncAgent.h"
#include "macros.h"
#include "BankDatabase.h"
#include "BankServer.h"
#include "CommandLineHelper.h"
#include <string>
#include <sstream>
#include <gtest/gtest.h>

using namespace std;

int 
server_init (int argc, char **argv)
  {
  // open the connection to the bank database
  const int len = 100;
  char hostname[len];
  gethostname (hostname, len);
  string dbName (hostname);
  dbName += ".db";
  g_bankDb.Open (dbName);

  // print help
  if (argc == 1 ||
      FindCommandlineKey (argc, argv, "--help")  || 
      FindCommandlineKey (argc, argv, "-h"))
    {
    cout << "Usage: " << argv[0] << " -b=HOSTNAME [Bank Server Options] [Test Selection]" << endl;
    cout                                                                                  << endl;
    cout << "Bank Server Options:"                                                        << endl;
    cout                                                                                  << endl;
    cout << "   -b --backup=HOSTNAME  [required] hostname of the backup Bank server"      << endl;
    cout << "   -h --help             show this message"                                  << endl;
    cout << "      --gtest            run the self-test module"                           << endl;
    cout                                                                                  << endl;

    argc = 2;
    argv[1] = "--help";
    ::testing::InitGoogleTest (&argc, argv);
    int ret = RUN_ALL_TESTS();

    cout                                                                                  << endl;
    cout << "Author: THONG, Wang Kit Wilson (50419704)"                                   << endl;
    cout << "Remark: This program was written in April 2011, for the course CS6223"       << endl;
    cout << "offered by CityU of HK. The source code can be downloaded from"              << endl;
    cout << "http://code.google.com/p/cs6223-2011-bank-system/source/list"                << endl;
    cout                                                                                  << endl;

    exit (ret);
    }

  // open the connection to the remote backup server
  string backupSvcName;
  if (ParseCommandlineArg (argc, argv, "--backup=", backupSvcName) || 
      ParseCommandlineArg (argc, argv, "-b=", backupSvcName))
    {
    g_syncAgent.Open (g_bankDb.GetDatabaseName (), backupSvcName);
    g_syncAgent.Sync ();
    g_syncAgent.SyncToMe ();
    }
  else
    {
    DEBUG_ERR ("g_syncAgent is not set as --backup is not found!");
    exit (0);
    }

  if (FindCommandlineKey (argc, argv, "--gtest") ||
      ContainCommandlineKey (argc, argv, "--gtest_"))
    {
    ::testing::InitGoogleTest (&argc, argv);
    return RUN_ALL_TESTS();
    }
  }

void 
Sync ()
  {
  g_syncAgent.Sync ();
  }
